﻿<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<jsp:useBean id="dateValue" class="java.util.Date"/>

<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE html>
<html lang="en">
<head>
    <base href="<%=basePath%>">
    <!-- jsp文件头和头部 -->
    <%@ include file="../admin/top.jsp" %>

    <style>
        table tr td img {
            height: 25px;
            border-radius: 8%;
        }

    </style>
</head>
<body>
<div class="container-fluid" id="main-container">

    <div id="page-content" class="clearfix">
        <div class="row-fluid">
            <div class="row-fluid">
                <!-- 检索  -->
                <form action="device/list" method="post" name="userForm" id="userForm">
                    <input type="hidden" name="menuId" value="${page.menuId}">
                    <table style="width: 55%">
                        <tr>
                            <td>
                                <span class="input-icon">
                                    <input style="margin-top: 0px;" autocomplete="off" type="text" id="imeiNum"
                                           name="searchValue" value="${page.searchValue}" placeholder="设备imei号"/>
                                </span>
                            </td>
                            <td>
                                <span class="input-icon">
                                    <input style="margin-top: 0px;" autocomplete="off" id="name" type="text"
                                           name="name" value="${name}" placeholder="设备昵称"/>
                                </span>
                            </td>
                            <td>
                                <span class="input-icon">
                                    <input style="margin-top: 0px;" autocomplete="off" id="phone" type="text"
                                           name="phone" value="${phone}" placeholder="设备手机号"/>
                                </span>
                            </td>
                            <td style="vertical-align:top;">
                                <select  id="channelCode" name="channelCode" data-values="${channels}"
                                        data-placeholder="请选择渠道" style="vertical-align:top;width: 120px;">
                                    <option value="">选择渠道商</option>
                                    <c:forEach items="${channels}" var="channel">
                                        <option value="${channel.channelCode}"
                                                <c:if test="${channel.channelCode eq channelCode}">selected</c:if> >${channel.name}</option>
                                    </c:forEach>
                                </select>
                            </td>
                            <td style="vertical-align:top;">
                                <select  name="deviceModelId" id="deviceModelId" data-placeholder="请选择设备型号" style="vertical-align:top;width: 150px;">
                                    <option value=""> 请选择设备型号</option>
                                    <%--<c:forEach items="${deviceModels}" var="model">
                                        <option value="${model.id}"
                                                <c:if test="${model.id eq deviceModel}">selected</c:if> >${model.name}</option>
                                    </c:forEach>--%>
                                </select>
                            </td>
                            <td style="vertical-align:top;">
                                <button class="btn btn-mini btn-light" onclick="search();" title="检索">
                                    <i id="nav-search-icon" class="icon-search"></i>
                                </button>
                            </td>
                            <td style="vertical-align:top;width: 8%">
                                 <c:if test="${fn:contains(butSet, 'import')}">
                                     <a class="btn btn-small btn-success" onclick="importData();" style="margin-left:10px;width: 60px;">导出数据</a>
                                 </c:if>
                            </td>
                            <td style="vertical-align:top;">
                                <c:if test="${fn:contains(butSet, 'add')}">
                                    <a class="btn btn-small btn-success" onclick="add();">新增</a>
                                </c:if>
                            </td>
                        </tr>
                    </table>
                    <!-- 检索  -->
                    <table id="table_report" class="table table-striped table-bordered table-hover">
                        <thead>
                        <tr>
                            <th>生产批次</th>
                            <th>IMEI/MEID</th>
                            <th>昵称</th>
                            <th>渠道商</th>
                            <th>设备手机号</th>
                            <th>位置</th>
                            <th>定位时间</th>
                            <th>电量</th>
                            <th>今日步数</th>
                            <th>导入系统时间</th>
                            <th>首次登录时间</th>
                            <th>最后一次登录时间</th>
                            <th>设备型号</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        <!-- 开始循环 -->
                        <c:choose>
                            <c:when test="${not empty devices}">
                                <c:forEach items="${devices}" var="device">
                                    <tr style="text-align: center">
                                        <td>${device.productionBatch }</td>
                                        <td>${device.id }</td>
                                        <td>${device.name }</td>
                                        <td>${device.channel.name }</td>
                                        <td>${device.phone }</td>
                                        <td>
                                            <c:if test="${not empty device.nowloc.addr || (not empty device.nowloc.lon && not empty device.nowloc.lat)}">
                                                ${String.format("%s(%s,%s)", (device.nowloc.addr == null)?"":device.nowloc.addr, device.nowloc.lon, device.nowloc.lat)}
                                            </c:if>
                                        </td>
                                        <td>
                                            <c:if test="${not empty device.nowloc.timestamp}">
                                                <jsp:setProperty name="dateValue" property="time"
                                                                 value="${device.nowloc.timestamp}000"/>
                                                <fmt:formatDate value="${dateValue}" pattern="yyyy-MM-dd HH:mm:ss"/>
                                            </c:if>
                                        </td>
                                        <td>${device.battery }</td>
                                        <td>${device.step }</td>
                                        <td><fmt:formatDate value="${device.importTime }"
                                                            pattern="yyyy-MM-dd HH:mm:ss"/></td>
                                        <td><fmt:formatDate value="${device.firstLoginTime }"
                                                            pattern="yyyy-MM-dd HH:mm:ss"/></td>
                                        <td><fmt:formatDate value="${device.lastLoginTime }"
                                                            pattern="yyyy-MM-dd HH:mm:ss"/></td>
                                        <td>${device.model }</td>
                                        <td>
                                            <a class="btn btn-mini" onclick="operateDev('${device.id}', 0)">定位</a>
                                            <p></p>
                                            <a class="btn btn-mini" onclick="operateDev('${device.id}', 1)">远程关机</a>
                                            <p></p>
                                            <a class="btn btn-mini" onclick="operateDev('${device.id}', 2)">关闭换卡解绑</a>
                                        </td>
                                    </tr>
                                </c:forEach>
                            </c:when>
                            <c:otherwise>
                                <tr class="main_info">
                                    <td colspan="10" class="center">没有相关数据</td>
                                </tr>
                            </c:otherwise>
                        </c:choose>
                        </tbody>
                    </table>
                    <div class="page-header position-relative">
                        <table style="width:100%;">
                            <tr>
                                <td style="vertical-align:top;">
                                    <div class="pagination"
                                         style="float: right;padding-top: 0px;margin-top: 0px;">${page.pageStr}</div>
                                </td>
                            </tr>
                        </table>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<!-- 返回顶部  -->
<a href="#" id="btn-scroll-up" class="btn btn-small btn-inverse">
    <i class="icon-double-angle-up icon-only"></i>
</a>
<!-- 引入 -->
<script type="text/javascript">window.jQuery || document.write("<script src='static/js/jquery-1.9.1.min.js'>\x3C/script>");</script>
<script src="static/js/bootstrap.min.js"></script>
<script src="static/js/ace-elements.min.js"></script>
<script src="static/js/ace.min.js"></script>

<script type="text/javascript" src="static/js/chosen.jquery.min.js"></script><!-- 下拉框 -->
<script type="text/javascript" src="static/js/bootstrap-datepicker.min.js"></script><!-- 日期框 -->
<script type="text/javascript" src="static/js/bootbox.min.js"></script><!-- 确认窗口 -->
<!-- 引入 -->
<script type="text/javascript" src="static/js/jquery.tips.js"></script><!--提示框-->
<script type="text/javascript">
    $(top.hangge());

    //检索
    function search() {
        top.jzts();
        $("#userForm").submit();
        //updateDevModels();
    }
    function operateDev(imei, type) {
        var msg = "";
        if(type == 0){
            msg = "确定要定位吗?";
        }else if(type == 1){
            msg = "确定要远程关机吗?";
        } else if(type == 2) {
            msg = "确定要关闭换卡解绑吗?"
        }
        bootbox.confirm(msg, function (result) {
            if (result) {
                top.jzts();
                var url = "<%=basePath%>device/operateDev";
                var postParam = {"id": imei, "operate": type};
                $.post(url, postParam, function (data) {
                    top.Dialog.close();
                    if (data.code == 200) {
                        top.hangge();
                        if(type == 0){
                            alert("定位成功");
                        }else if(type == 1){
                            alert("远程关机成功");
                        } else if(type == 2) {
                            alert("关闭换卡解绑成功");
                        }
                    } else {
                        alert("操作失败:"+data.msg)
                    }
                });
            }
        })
    }

    //动态选择设备型号
    function updateDevModels() {
        var channelId = document.getElementById('channelCode').value;
        var devModelSelect = document.getElementById('deviceModelId');
        // 清空当前的所有选项
        devModelSelect.innerHTML = '<option value="">请选择设备型号</option>';
        //console.log("方法执行了,channelId的值为："+channelId);
        // 假设 devModels 是一个包含设备型号的数组
        // 遍历 devModels 并根据 channelId 过滤选项
        <c:forEach items="${deviceModels}" var="deviceModel">
        if ("${deviceModel.vender}" == channelId) {
            var option = document.createElement('option');
            option.value = '${deviceModel.id}';
            option.text = '${deviceModel.model}';
            if('${deviceModel.id}' == '${deviceModelId}') {
               option.selected = true;
            }
            devModelSelect.add(option);
        }
        </c:forEach>
        // 手动触发 select 元素的 change 事件
        devModelSelect.dispatchEvent(new Event('change'));
    }

    document.addEventListener("DOMContentLoaded", function () {
        const selectElement = document.getElementById("channelCode");
        let lastSelectedValue = selectElement.value;

        // 1️⃣ 监听用户手动更改选项
        selectElement.addEventListener("change", function () {
            //console.log("用户手动更改了选项，触发 updateDevModels()");
            updateDevModels();
        });

        // 2️⃣ 监听 select 内部的 option 变化（适用于 AJAX 动态更新）
        const observer = new MutationObserver(() => {
            //console.log("检测到 <option> 变化，自动触发 updateDevModels()");
            updateDevModels();
        });
        observer.observe(selectElement, { childList: true, subtree: true });

        // 3️⃣ 监听选中项变化（即使是 JavaScript 代码修改）
        setInterval(() => {
            if (selectElement.value !== lastSelectedValue) {
                //console.log("检测到选中项变化，自动触发 updateDevModels()");
                lastSelectedValue = selectElement.value;
                updateDevModels();
            }
        }, 500);

        // 4️⃣ 确保在动态更新 select 选项后，手动调用 updateDevModels()
        function updateSelectOptions(newOptions) {
            selectElement.innerHTML = '<option value="">选择渠道商</option>'; // 清空旧选项
            newOptions.forEach(optionData => {
                let option = document.createElement("option");
                option.value = optionData.value;
                option.text = optionData.text;
                selectElement.appendChild(option);
            });
            //console.log("选项更新完成，手动触发 updateDevModels()");
            updateDevModels(); // **手动调用，确保更新后立即触发**
        }
        // 5️⃣ 页面加载后执行一次
        updateDevModels();

        // 绑定 deviceModelId 的 change 事件
        document.getElementById('deviceModelId').addEventListener('change', function () {
            var selectedValue = this.value;
            //console.log("设备型号已选择：" + selectedValue);
        });

       /* document.getElementById('userForm').addEventListener('submit', function (e) {
            var selectedDeviceModelId = document.getElementById('deviceModelId').value;
            console.log("提交前选中的设备型号ID：" + selectedDeviceModelId);
        });*/
    });

    //导出数据
    function importData(){
        var url = "<%=basePath%>device/import" +
            "?imei=" + encodeURIComponent($("#imeiNum").val()) +
            "&name=" + encodeURIComponent($("#name").val()) +
            "&phone=" + encodeURIComponent($("#phone").val()) +
            "&channelCode=" + encodeURIComponent($("#channelCode").val()) +
            "&deviceModelId=" + encodeURIComponent($("#deviceModelId").val()) ;
        window.open(url);
    }

</script>

<script type="text/javascript">
    $(function () {
        //日期框
        $('.date-picker').datepicker({autoclose: true});
        //下拉框
        $(".chzn-select").chosen();
        $(".chzn-select-deselect").chosen({allow_single_deselect: true});
        //复选框
        $('table th input:checkbox').on('click', function () {
            var that = this;
            $(this).closest('table').find('tr > td:first-child input:checkbox')
                .each(function () {
                    this.checked = that.checked;
                    $(this).closest('tr').toggleClass('selected');
                });
        });
    });
</script>
</body>
</html>
